package com.example.sqliteviewer;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

public class QueryActivity extends AppCompatActivity {

    private String databasePath;
    private SQLiteDatabase database;
    private EditText etSqlQuery;
    private TableLayout tableLayout;
    private TextView tvQueryResult;
    private TextView tvEmptyResult;
    private HorizontalScrollView scrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query);
        
        databasePath = getIntent().getStringExtra("DATABASE_PATH");
        if (databasePath == null) {
            Toast.makeText(this, "数据库路径无效", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        setTitle("执行SQL查询");
        
        etSqlQuery = findViewById(R.id.etSqlQuery);
        Button btnExecute = findViewById(R.id.btnExecute);
        tableLayout = findViewById(R.id.tableLayout);
        tvQueryResult = findViewById(R.id.tvQueryResult);
        tvEmptyResult = findViewById(R.id.tvEmptyResult);
        scrollView = findViewById(R.id.scrollView);
        
        try {
            database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READONLY);
        } catch (Exception e) {
            Toast.makeText(this, "无法打开数据库: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        btnExecute.setOnClickListener(v -> executeQuery());
        
        // 默认查询示例
        etSqlQuery.setText("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'android_%'");
    }
    
    private void executeQuery() {
        String sql = etSqlQuery.getText().toString().trim();
        if (sql.isEmpty()) {
            Toast.makeText(this, "请输入SQL查询语句", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 清除之前的结果
        tableLayout.removeAllViews();
        tvQueryResult.setText("");
        
        try {
            // 检查是否是SELECT查询
            if (!sql.toUpperCase().startsWith("SELECT")) {
                // 非SELECT查询（如INSERT, UPDATE, DELETE等）
                database.execSQL(sql);
                tvQueryResult.setText("查询执行成功");
                tvEmptyResult.setVisibility(View.VISIBLE);
                scrollView.setVisibility(View.GONE);
                return;
            }
            
            // 执行SELECT查询
            Cursor cursor = database.rawQuery(sql, null);

            int rowCount = cursor.getCount();
            tvQueryResult.setText("查询结果: " + rowCount + " 行");

            if (rowCount > 0 && cursor.moveToFirst()) {
                // 创建表头
                TableRow headerRow = new TableRow(this);
                headerRow.setBackgroundColor(ContextCompat.getColor(this, R.color.header_background));

                // 添加行号列
                TextView rowNumHeader = createTextView("#", true);
                headerRow.addView(rowNumHeader);

                // 添加列名
                String[] columnNames = cursor.getColumnNames();
                for (String columnName : columnNames) {
                    TextView headerText = createTextView(columnName, true);
                    headerRow.addView(headerText);
                }

                tableLayout.addView(headerRow);

                // 显示数据行
                int rowNum = 1;
                do {
                    TableRow dataRow = new TableRow(this);

                    // 设置交替行背景色
                    if (rowNum % 2 == 0) {
                        dataRow.setBackgroundColor(ContextCompat.getColor(this, R.color.row_even));
                    } else {
                        dataRow.setBackgroundColor(ContextCompat.getColor(this, R.color.row_odd));
                    }

                    // 添加行号
                    TextView rowNumText = createTextView(String.valueOf(rowNum), false);
                    dataRow.addView(rowNumText);

                    // 添加数据
                    for (int i = 0; i < columnNames.length; i++) {
                        String value = "";

                        if (!cursor.isNull(i)) {
                            switch (cursor.getType(i)) {
                                case Cursor.FIELD_TYPE_INTEGER:
                                    value = String.valueOf(cursor.getLong(i));
                                    break;
                                case Cursor.FIELD_TYPE_FLOAT:
                                    value = String.valueOf(cursor.getDouble(i));
                                    break;
                                case Cursor.FIELD_TYPE_STRING:
                                    value = cursor.getString(i);
                                    break;
                                case Cursor.FIELD_TYPE_BLOB:
                                    value = "[BLOB]";
                                    break;
                                case Cursor.FIELD_TYPE_NULL:
                                    value = "NULL";
                                    break;
                            }
                        } else {
                            value = "NULL";
                        }

                        TextView dataText = createTextView(value, false);
                        dataRow.addView(dataText);
                    }

                    tableLayout.addView(dataRow);
                    rowNum++;

                } while (cursor.moveToNext());

                tvEmptyResult.setVisibility(View.GONE);
                scrollView.setVisibility(View.VISIBLE);
            } else {
                // 查询结果为空
                tvEmptyResult.setVisibility(View.VISIBLE);
                scrollView.setVisibility(View.GONE);
            }

            cursor.close();

        } catch (Exception e) {
            tvQueryResult.setText("查询执行失败: " + e.getMessage());
            tvEmptyResult.setVisibility(View.VISIBLE);
            scrollView.setVisibility(View.GONE);
            e.printStackTrace();
        }
    }
    
    private TextView createTextView(String text, boolean isHeader) {
        TextView textView = new TextView(this);
        textView.setText(text);
        textView.setPadding(16, 16, 16, 16);
        
        if (isHeader) {
            textView.setTextColor(ContextCompat.getColor(this, R.color.header_text));
            //textView.setTextAppearance(R.style.TextAppearance_AppCompat_Medium);
            textView.setTypeface(null, android.graphics.Typeface.BOLD);
        } else {
            textView.setTextColor(ContextCompat.getColor(this, R.color.data_text));
        }
        
        return textView;
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (database != null && database.isOpen()) {
            database.close();
        }
    }
}